package com.google.code.pokerstats_service.math;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.google.code.pokerstats_service.Game;
import com.google.code.pokerstats_service.PlayerResult;
import com.google.code.pokerstats_service.PlayerStats;

/**
 * Calculates basic player statistics: games played, total buy-ins and
 * cash-outs, expectation and standard deviation.
 * 
 * @author DL
 */
public class BasicStatsCalculator {
    /** Constructor. */
    public BasicStatsCalculator() {}
    
    public void updateStats(
	    Map<Game, Set<PlayerResult>> games, Map<Long, PlayerStats> playersStats) {
	
        Map<Long, Double> playerToSumSquares = new HashMap<Long, Double>();
        for (PlayerStats stats : playersStats.values()) {
            stats.gamesPlayed = 0;
            stats.totalBuyIns = 0.0;
            stats.totalCashOuts = 0.0;
            stats.expectation = 0.0;
            stats.stdev = 0.0;
            
            playerToSumSquares.put(stats.fbUid, 0.0);
        }
        
        for (Game game : games.keySet()) {
            for (PlayerResult playerResult : games.get(game)) {
                PlayerStats stats = playersStats.get(playerResult.player);
                ++stats.gamesPlayed;
                stats.totalBuyIns += playerResult.buyIn;
                stats.totalCashOuts += playerResult.cashOut;
                
                double profit = playerResult.cashOut - playerResult.buyIn;
                Double tmp = playerToSumSquares.get(playerResult.player);
                playerToSumSquares.put(playerResult.player, tmp + (profit * profit));
            }
        }
        for (PlayerStats stats : playersStats.values()) {
            if (stats.gamesPlayed > 0) {
                double exp =
                    (stats.totalCashOuts - stats.totalBuyIns) / stats.gamesPlayed;
                
                stats.expectation = exp;
                stats.stdev = Math.sqrt(
                    (playerToSumSquares.get(stats.fbUid) / stats.gamesPlayed) -
                    (exp * exp));
            }
        }
    }
}